Rolling Window Calculations On A Pandas DataFrame

Overview:

  • Rolling window calculations involve taking subsets of data, where subsets are of the same or varying length and performing mathematical calculations on them.

  • The pandas Rolling class supports rolling window calculations on Series and DataFrame classes.

  • Rolling class has the popular math functions like sum(), mean() and other related functions implemented. Through the apply() method custom math operations can be performed on a rolling window.

Example:

# Example Python program that performs rolling
# window calculations on a pandas DataFrame

import pandas as pds

metrics = {"Pressure":(90, 92, 91, 95, 94),
           "FlowRate":(35, 36, 36, 38, 37)};

df = pds.DataFrame(data = metrics,
                   index = ("Sensor 1", "Sensor 2", "Sensor 3",
                               "Sensor 4", "Sensor 5"));

# Sum every two metrics
print(df.rolling(window=2).sum());

Output:

          Pressure  FlowRate
Sensor 1       NaN       NaN
Sensor 2     182.0      71.0
Sensor 3     183.0      72.0
Sensor 4     186.0      74.0
Sensor 5     189.0      75.0

Copyright 2024 © pythontic.com